package xyz.ranyh.jobclient.http;

import android.os.AsyncTask;
import android.util.Log;

import org.json.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import xyz.ranyh.jobclient.util.User;
import xyz.ranyh.jobclient.util.UserParser;


public class Resource {
    public volatile String token = "";
    public volatile long expired = -1;
    private static Resource instance = null;
    public int statusCode = 200;

    OkHttpClient client = new OkHttpClient();

    private User user;

    private Resource() {}
    static public Resource getInstance() {
        if (instance == null) {
            instance = new Resource();
            instance.user = new UserParser().parse();
        }

        return instance;
    }

    public boolean isLogin() {
        if (token == "" || new Date().getTime() > expired) {
            token = "";
            return false;
        }

        return true;
    }

    public String login(String email, String password) {
        JSONTokener body = null;

        try {
            String credential = Credentials.basic(email, password);
            Request request =  new Request.Builder()
                    .url(Url.LOGIN_URL)
                    .addHeader("Authorization", credential)
                    .addHeader("accept", "application/json")
                    .build();

            Response response = client.newCall(request).execute();
            statusCode = response.code();

            body = new JSONTokener(response.body().string());
            JSONObject resJson = (JSONObject) body.nextValue();
            expired = (new Date().getTime() + resJson.getInt("expiration") * 1000);

            token = resJson.getString("token");

            if (user == null) {
                user = new User();
            }
            user.setEmail(email);
            user.setPassword(password);

            return token;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void syncUserInfo(String email) {
        new GetUserInfoTask(email).execute();
    }

    public User getUser() {
        return user;
    }

    public class GetUserInfoTask extends AsyncTask<Void, Void, Boolean>
    {
        private String mEmail = null;

        GetUserInfoTask(String email) {
            mEmail = email;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            JSONTokener bodyJson = null;
            String body = "";
            try {
                String credential = Credentials.basic(token, "");
                Log.d("Token", credential);
                Request request =  new Request.Builder()
                        .url(Url.UESR_URL+ mEmail)
                        .addHeader("Authorization", credential)
                        .addHeader("accept", "application/json")
                        .build();

                Response response = client.newCall(request).execute();
                statusCode = response.code();

                body = response.body().string();
                Log.d("User info", body);
                bodyJson = new JSONTokener(body);
                JSONObject resJson = (JSONObject) bodyJson.nextValue();

                user.setNickname(resJson.getString("nickname"));
                user.setRole(resJson.getString("role"));
                user.setCreateDate(resJson.getString("create_date"));
                JSONArray ja = resJson.getJSONArray("stared");

                List<Integer> tmp = new ArrayList<Integer>();
                for (int i = 0; i < ja.length(); ++i) {
                    tmp.add(ja.getInt(i));
                }
                user.setStar(tmp);

                ja = resJson.getJSONArray("alarm");
                tmp = new ArrayList<Integer>();
                for (int i = 0; i < ja.length(); ++i) {
                    tmp.add(ja.getInt(i));
                }
                user.setAlarm(tmp);

                new UserParser().save(user);

            } catch (JSONException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            return true;
        }
    }

    public boolean logout() {
        token = null;
        expired = -1;
        user = null;
        return new UserParser().clear();
    }
}
